package com.ziq.zcamp.post

import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.ziq.base.extension.launchWithTryAsynchronous
import com.ziq.zcamp.api.repository.DefaultPostTopicsRepository
import com.ziq.zcamp.api.repository.PostTopicsRepository
import com.ziq.zcamp.bean.topics.TopicsInfo
import com.ziq.zcamp.util.list.ObservableArrayList2
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class TopicsViewModel @Inject constructor() : ViewModel() {

    val mTopicsList = ObservableArrayList2<TopicsInfo>()
    private var key :String ?= null
    private val mHandler = Handler(Looper.getMainLooper())
    private val searchRunnable = Runnable {
        requestData()
    }

    private val mRepository : PostTopicsRepository by lazy {
        DefaultPostTopicsRepository()
    }

    fun init() {
    }

    fun searchTopics(key : String?){
        this.key = key
        mHandler.removeCallbacks(searchRunnable)
        mHandler.postDelayed(searchRunnable, 1000)
    }

    fun requestData(){
        launchWithTryAsynchronous(whenTry = {
            val list = mRepository.topicSearch(key?:"")
            if (list.isEmpty()){
                val empty = TopicsInfo()
                empty.name = key
                empty.needCreate = true
                mTopicsList.clearAndAddAll(listOf(empty))
            }else{
                mTopicsList.clearAndAddAll(list)
            }

        }, whenCatch = {

        })
    }
}